package com.asa.recycleview

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup

/**
 * create By：anderson
 * on 2022/3/14
 * desc:
 */
class RecycleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {



    private var firstRow = 0
    private var rowCount = 0
    private var currentY = 0
    private var needRelayout = false

    private var mWidth = 0
    private var mHeight = 0
    private val viewList  = mutableListOf<View>()  // 当前显示的view集合

    private var touchSlop = 0  //最小滑动距离
    private var mScrollY = 0 //y轴方向的偏移量

    private  lateinit var adapter:Adapter  // 适配器
    private lateinit var heights : IntArray

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //测量所有子view的高度之和  类适配wrap_content
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (adapter != null){
            val count = adapter.getCount()
            heights = IntArray(count)
            for (index in 0 .. count){
                heights[index] = adapter.getHeight(index)
            }
        }

        val sumHeight = sumArray(heights, 0, heights.size)
        setMeasuredDimension(widthSize,Math.min(sumHeight,heightSize))
    }


    private fun sumArray(array:IntArray,firstIndex:Int,endIndex:Int):Int{
        var sum= 0
        var count = firstIndex + endIndex
        for (index in firstIndex .. count){
            sum += array[index]
        }
        return sum

    }



    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {

    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return super.onInterceptTouchEvent(ev)

    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return super.onTouchEvent(event)
    }

    override fun scrollBy(x: Int, y: Int) {
        super.scrollBy(x, y)
    }


    interface Adapter{
        fun onCreateViewHodler(position: Int, convertView: View?, parent: ViewGroup?): View?
        fun onBinderViewHodler(position: Int, convertView: View?, parent: ViewGroup?): View?

        //Item的类型
        fun getItemViewType(row: Int): Int

        //Item的类型数量
        fun getViewTypeCount(): Int
        fun getCount(): Int
        fun getHeight(index: Int): Int

    }

}